// box
const boxLoginForm = document.querySelector(".form__login");
const boxSignupFormm = document.querySelector(".form__signUp");
//  login form
const loginForm = document.getElementById("loginForm");
const loginEmail = document.getElementById("loginEmail");
const loginPassword = document.getElementById("loginPassword");
const loginRemember = document.getElementById("loginRemember");
// signup form
const signupForm = document.getElementById("signupForm");
const signupEmail = document.getElementById("signupEmail");
const phoneNumber = document.getElementById("phoneNumber");
const signupPassword = document.getElementById("signupPassword");
const signupConfirmPassword = document.getElementById("signupConfirmPassword");
const terms = document.getElementById("terms");

const loginSubmit = document.getElementById("loginSubmit");

//  links
const loginLink = document.querySelector(".form__login--link");

// password show and hide
const passShowHide = document.querySelectorAll(".showHide");

//  show and hide password
passShowHide.forEach((eye) => {
  eye.addEventListener("click", () => {
    const parentEl = eye.parentElement;
    const passinput = parentEl.querySelector("input");
    if (passinput.type === "password") {
      passinput.type = "text";
      eye.name = "eye-outline";
    } else {
      passinput.type = "password";
      eye.name = "eye-off-outline";
    }
  });
});

function testPNumber() {
  if (!phoneNumber.value) {
    alert("请填写手机号！");
    return false;
  } else if (!/^1[3-9]\d{9}$/.test(phoneNumber.value)) {
    alert("手机号格式不正确！");
    return false;
  }
  return true;
}

// make validation to email
function testEmail(email) {
  if (!email.value) {
    alert("Email is required");
    return false;
  } else if (!/^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/.test(email.value)) {
    alert("Please enter a valid email address");
    return false;
  }
  return true;
}

// make validation to password
function testPassword(password) {
  if (!password.value) {
    alert("Password is required");
    return false;
  } else if (password.value.length < 8) {
    alert("Password must be at least 8 characters long");
    return false;
  } else if (!/^(?=.*[A-Z])(?=.*\d).{8,}$/.test(password.value)) {
    alert("Password must contain at least one uppercase letter and one number");
    return false;
  }
  return true;
}

function testRememberMe(terms) {
  if (!terms.checked) {
    alert("Please accept the terms and conditions");
    return false;
  }
  return true;
}

function testConfirmPassowrd(signupConfirmPassword, signupPassword) {
  if (signupConfirmPassword.value !== signupPassword.value) {
    alert("Passwords don't match");
    return false;
  }
  return true;
}

function formValidation(
  form,
  pNumber,
  // email,
  // password,
  // confirm = 1,
  // terms = 1,
  // signup = true
) {
  if (!testPNumber(pNumber)) return false;
}

loginForm.addEventListener("submit", (e) => {
  e.preventDefault();
  formValidation(loginForm, phoneNumber);
  saveUserInfo();
});


var openid_ = '';
var phone_ = '';
var type = 1;

function getOpenId(code) {
  let api = '/App/User/GetOpenId';
  let data = {code: code};
  ajax('get', api, data, (res) => {
    let info = res.data
    if (info.phone) {
      phone_ = info.phone;
      loginSubmit.innerText = '重新绑定';
      phoneNumber.value = phone_;
      type = 2;

      document.getElementById('unbind').style.display = '';
      document.getElementById('unbind').addEventListener('click', unbindOpenid);
      document.getElementById('unbind').style.marginTop = '10rem';
      document.getElementById('launch-btn').style.display = 'none';
      document.getElementById('formInput').style.height = '5rem';
      loginForm.style.gap = '2';
      document.getElementById('phoneNumber').style.display = '';
    }
    if (info.openid) {
      openid_ = info.openid;
      let wxDom = document.querySelector('wx-open-launch-weapp');
      wxDom.setAttribute('path', wxDom.getAttribute('path') + '?openId=' + openid_);
      wxDom.setAttribute('appid', getAppId2());
      getWxConfig();
    } else {
      alert('请刷新后重试！');
    }

  }, (e) => {
    console.log(e)
  });
}

function saveUserInfo() {
  let api = '/App/User/SaveUserInfo';
  let data = {openid: openid_, Phoen: phoneNumber.value, type: type};
  ajax('get', api, data, (data) => {
    if (data.statusCode === 200) {
      console.log(data);
      loginSubmit.innerText = '重新绑定';
      type = 2;
      // alert('绑定成功！');
      if (confirm("绑定成功！点击确定退出页面")) {
        WeixinJSBridge.call('closeWindow');
      }

    } else {
      // alert(data.errors);
      if (confirm(data.errors + "！点击确定退出页面")) {
        WeixinJSBridge.call('closeWindow');
      }
    }
  }, (e) => {
    alert(e.errors || '绑定失败！');
    console.log(e)
  });
}


function getWxCode() {
  var code_ = '';
  let isWechat = String(navigator.userAgent.toLowerCase().match(/MicroMessenger/i)) === "micromessenger";
  if (true) {
    let appid = getAppId();//"wx5cc8c0419df1e40d";
    let code = this.getUrlCode().code; //是否存在code
    let local = window.location.href;//.split('http://')[1]||window.location.href.split('https://')[1];

    if (window.sessionStorage.code && typeof WeixinJSBridge !== 'undefined') {
      document.addEventListener('WeixinJSBridgeReady', function () {
        WeixinJSBridge.call('closeWindow');
      }, false);
      WeixinJSBridge.call('closeWindow');
      return;
    }

    if (code == null || code === "") {//snsapi_base,snsapi_userinfo
      let href =
        "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
        appid +
        "&redirect_uri=" +
        encodeURIComponent(local) +
        "&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
      //不存在就打开上面的地址进行授权
      window.location.href = href;

      // history.pushState(null, '', location.href);
      // location.replace(href);

    } else {
      code_ = code;
      window.sessionStorage.setItem('code', code);
      console.log('code_:' + code_);
      getOpenId(code_);
    }
  }
}

/*获取公众号的appid*/
function getAppId() {
  let hostname = window.location.hostname;
  if (hostname === 'hfj.asrj.net') {
    return 'wxd4ee1396dbebfb95'
  } else if (hostname === 'ryx.asrj.net') {
    return 'wx98e98c67122a469d'
  } else {
    return 'wx5cc8c0419df1e40d'//傲视
  }
}

/*获取小程序appid*/
function getAppId2() {
  let hostname = window.location.hostname;
  if (hostname === 'hfj.asrj.net') {
    return 'wx0b8dac82e868ea1c'
  } else if (hostname === 'ryx.asrj.net') {
    return 'wxff6a17381574e4be'
  } else {
    return 'wx26d0959a95fe9661'//傲视
  }
}

function getWxConfig() {
  //获取微信JS-SDK配置用于打开小程序
  let api = '/App/User/GetsignatureList';
  let data = {
    url: window.location.href.replace(/#.*$/, '')
  };
  ajax('get', api, data, (data) => {
    data = data.data;
    let config = {
      debug: false,
      appId: getAppId(),
      timestamp: data.timestamp,
      nonceStr: data.noncestr,
      signature: data.signature,
      jsApiList: ['onMenuShareTimeline'], // 必填，需要使用的JS接口列表
      openTagList: ['wx-open-launch-weapp']
    };
    wx.config({
      ...config
    });
    wx.ready((e) => {
      document.querySelector(".loading-container").remove();
      console.log('跳转小程序按钮ready:', e)
    });
    wx.error((res) => {
      //config信息验证失败会执行error函数，如签名过期导致验证失败，具体错误信息可以打开config的debug模式查看，也可以在返回的res参数中查看，对于SPA可以在这里更新签名。
      console.log('跳转小程序按钮error:', res)
    });
  }, (e) => {
    if (confirm("请重新进入该网页！")) {
      document.querySelector(".loading-container").remove();
      WeixinJSBridge.call('closeWindow');
    }
  });
}


function unbindOpenid() {
  console.log(openid_)


  if (confirm("确定要取消绑定吗？")) {
    let api = '/App/User/Unbinding';
    let data = {
      phone: phone_,
      openid: openid_
    };
    ajax('get', api, data, (data) => {
      window.sessionStorage.setItem('code', '');
      history.replaceState(null, '', location.href);
      history.replaceState({}, document.title, location.href.split('?')[0]);
      getWxCode();
    }, (e) => {
    });
  }

}

